import QtQuick 2.15
import QtQuick.Controls 2.15
import QtQuick.Layouts 1.15
import "../../components" as Components
import "../../styles" as Styles

ScrollView {
    id: taskDetailsView

    // 自定义属性
    property var task: null
    property bool editMode: false

    // 信号
    signal taskModified(var task)

    clip: true
    contentWidth: availableWidth

    // 美化滚动条
    ScrollBar.vertical: ScrollBar {
        id: verticalScrollBar
        policy: ScrollBar.AsNeeded

        contentItem: Rectangle {
            implicitWidth: 6
            implicitHeight: 6
            radius: 3
            color: Styles.Theme.primary
            opacity: verticalScrollBar.pressed ? 0.8 : (verticalScrollBar.hovered ? 0.6 : 0.4)

            Behavior on opacity {
                NumberAnimation { duration: 200 }
            }
        }

        background: Rectangle {
            implicitWidth: 6
            color: Styles.Theme.surfaceVariant
            opacity: 0.2
        }
    }

    ColumnLayout {
        width: taskDetailsView.availableWidth
        spacing: Styles.Theme.spacingNormal

        // 基本信息区域
        Rectangle {
            Layout.fillWidth: true
            Layout.preferredHeight: basicInfoColumn.height + Styles.Theme.spacingNormal * 2
            color: Styles.Theme.backgroundSecondary
            border.color: Styles.Theme.border
            border.width: 1
            radius: Styles.Theme.radiusSmall

            ColumnLayout {
                id: basicInfoColumn
                anchors.left: parent.left
                anchors.right: parent.right
                anchors.top: parent.top
                anchors.margins: Styles.Theme.spacingNormal
                spacing: Styles.Theme.spacingSmall

                Text {
                    text: qsTr("基本信息")
                    color: Styles.Theme.textPrimary
                    font.pixelSize: Styles.Theme.fontSizeNormal
                    font.weight: Styles.Theme.fontWeightMedium
                }

                GridLayout {
                    Layout.fillWidth: true
                    columns: 2
                    rowSpacing: Styles.Theme.spacingSmall
                    columnSpacing: Styles.Theme.spacingNormal

                    Text {
                        text: qsTr("任务名称:")
                        color: Styles.Theme.textSecondary
                        font.pixelSize: Styles.Theme.fontSizeSmall
                    }
                    Text {
                        text: formatTaskName(task)
                        color: Styles.Theme.textPrimary
                        font.pixelSize: Styles.Theme.fontSizeSmall
                        font.weight: Styles.Theme.fontWeightMedium
                        Layout.fillWidth: true
                        elide: Text.ElideRight
                    }

                    Text {
                        text: qsTr("任务状态:")
                        color: Styles.Theme.textSecondary
                        font.pixelSize: Styles.Theme.fontSizeSmall
                    }
                    Rectangle {
                        Layout.preferredWidth: 160
                        Layout.preferredHeight: 24
                        radius: 12
                        color: getStageColor(task ? task.currentSubTaskStage : -1)

                        Text {
                            anchors.centerIn: parent
                            text: formatSubTaskStatus(task)
                            color: Styles.Theme.textOnPrimary
                            font.pixelSize: 11
                            horizontalAlignment: Text.AlignHCenter
                        }
                    }

                    Text {
                        text: qsTr("子任务进度:")
                        color: Styles.Theme.textSecondary
                        font.pixelSize: Styles.Theme.fontSizeSmall
                    }
                    Text {
                        text: formatSubTaskProgress(task)
                        color: Styles.Theme.textPrimary
                        font.pixelSize: Styles.Theme.fontSizeSmall
                    }

                    Text {
                        text: qsTr("分配AGV:")
                        color: Styles.Theme.textSecondary
                        font.pixelSize: Styles.Theme.fontSizeSmall
                    }
                    Text {
                        text: task ? (task.assignedAgv || qsTr("未分配")) : ""
                        color: task && task.assignedAgv ? Styles.Theme.textPrimary : Styles.Theme.textSecondary
                        font.pixelSize: Styles.Theme.fontSizeSmall
                    }
                }
            }
        }

        // 时间信息区域
        Rectangle {
            Layout.fillWidth: true
            Layout.preferredHeight: timeInfoColumn.height + Styles.Theme.spacingNormal * 2
            color: Styles.Theme.backgroundSecondary
            border.color: Styles.Theme.border
            border.width: 1
            radius: Styles.Theme.radiusSmall

            ColumnLayout {
                id: timeInfoColumn
                anchors.left: parent.left
                anchors.right: parent.right
                anchors.top: parent.top
                anchors.margins: Styles.Theme.spacingNormal
                spacing: Styles.Theme.spacingSmall

                Text {
                    text: qsTr("时间信息")
                    color: Styles.Theme.textPrimary
                    font.pixelSize: Styles.Theme.fontSizeNormal
                    font.weight: Styles.Theme.fontWeightMedium
                }

                GridLayout {
                    Layout.fillWidth: true
                    columns: 2
                    rowSpacing: Styles.Theme.spacingSmall
                    columnSpacing: Styles.Theme.spacingNormal

                    Text {
                        text: qsTr("创建时间:")
                        color: Styles.Theme.textSecondary
                        font.pixelSize: Styles.Theme.fontSizeSmall
                    }
                    Text {
                        text: formatTime(task ? task.createTime : null)
                        color: Styles.Theme.textPrimary
                        font.pixelSize: Styles.Theme.fontSizeSmall
                        Layout.fillWidth: true
                    }

                    Text {
                        text: qsTr("持续时间:")
                        color: Styles.Theme.textSecondary
                        font.pixelSize: Styles.Theme.fontSizeSmall
                    }
                    Text {
                        text: formatDuration(task ? task.durationSeconds : 0)
                        color: Styles.Theme.textPrimary
                        font.pixelSize: Styles.Theme.fontSizeSmall
                        Layout.fillWidth: true
                    }
                }
            }
        }

        // 进度信息区域
        Rectangle {
            Layout.fillWidth: true
            Layout.preferredHeight: progressInfoColumn.height + Styles.Theme.spacingNormal * 2
            color: Styles.Theme.backgroundSecondary
            border.color: Styles.Theme.border
            border.width: 1
            radius: Styles.Theme.radiusSmall
            visible: task && (task.status === "executing" || task.status === "completed")

            ColumnLayout {
                id: progressInfoColumn
                anchors.left: parent.left
                anchors.right: parent.right
                anchors.top: parent.top
                anchors.margins: Styles.Theme.spacingNormal
                spacing: Styles.Theme.spacingSmall

                Text {
                    text: qsTr("执行进度")
                    color: Styles.Theme.textPrimary
                    font.pixelSize: Styles.Theme.fontSizeNormal
                    font.weight: Styles.Theme.fontWeightMedium
                }

                // 进度条
                Rectangle {
                    Layout.fillWidth: true
                    Layout.preferredHeight: 20
                    color: Styles.Theme.backgroundAlternate
                    radius: 10
                    border.color: Styles.Theme.border
                    border.width: 1

                    Rectangle {
                        anchors.left: parent.left
                        anchors.top: parent.top
                        anchors.bottom: parent.bottom
                        anchors.margins: 1
                        width: Math.max(0, Math.min(parent.width - 2, (task ? task.progress || 0 : 0) * (parent.width - 2) / 100))
                        color: getProgressColor(task ? task.progress || 0 : 0)
                        radius: 9

                        Text {
                            anchors.centerIn: parent
                            text: qsTr("%1%").arg(task ? Math.round(task.progress || 0) : 0)
                            color: Styles.Theme.textOnPrimary
                            font.pixelSize: 10
                            visible: parent.width > 40
                        }
                    }
                }

                Text {
                    text: qsTr("阶段: %1").arg(formatStageText(task ? task.currentSubTaskStage : -1))
                    color: Styles.Theme.textSecondary
                    font.pixelSize: Styles.Theme.fontSizeSmall
                    Layout.fillWidth: true
                }
            }
        }

        // 错误信息区域
        Rectangle {
            Layout.fillWidth: true
            Layout.preferredHeight: errorInfoColumn.height + Styles.Theme.spacingNormal * 2
            color: Styles.Theme.backgroundSecondary
            border.color: Styles.Theme.danger
            border.width: 1
            radius: Styles.Theme.radiusSmall
            visible: !!(task && task.status === "failed" && task.errorMessage)

            ColumnLayout {
                id: errorInfoColumn
                anchors.left: parent.left
                anchors.right: parent.right
                anchors.top: parent.top
                anchors.margins: Styles.Theme.spacingNormal
                spacing: Styles.Theme.spacingSmall

                RowLayout {
                    Layout.fillWidth: true

                    Text {
                        text: "⚠️"
                        font.pixelSize: Styles.Theme.fontSizeNormal
                    }

                    Text {
                        text: qsTr("错误信息")
                        color: Styles.Theme.danger
                        font.pixelSize: Styles.Theme.fontSizeNormal
                        font.weight: Styles.Theme.fontWeightMedium
                        Layout.fillWidth: true
                    }
                }

                Rectangle {
                    Layout.fillWidth: true
                    Layout.preferredHeight: errorText.height + 16
                    color: Styles.Theme.danger
                    opacity: 0.1
                    radius: Styles.Theme.radiusSmall

                    Text {
                        id: errorText
                        anchors.left: parent.left
                        anchors.right: parent.right
                        anchors.top: parent.top
                        anchors.margins: 8
                        text: task ? task.errorMessage || "" : ""
                        color: Styles.Theme.danger
                        font.pixelSize: Styles.Theme.fontSizeSmall
                        wrapMode: Text.WordWrap
                    }
                }
            }
        }

        // 任务参数区域
        Rectangle {
            Layout.fillWidth: true
            Layout.preferredHeight: paramsInfoColumn.height + Styles.Theme.spacingNormal * 2
            color: Styles.Theme.backgroundSecondary
            border.color: Styles.Theme.border
            border.width: 1
            radius: Styles.Theme.radiusSmall
            visible: !!(task && task.parameters && Object.keys(task.parameters || {}).length > 0)

            ColumnLayout {
                id: paramsInfoColumn
                anchors.left: parent.left
                anchors.right: parent.right
                anchors.top: parent.top
                anchors.margins: Styles.Theme.spacingNormal
                spacing: Styles.Theme.spacingSmall

                Text {
                    text: qsTr("任务参数")
                    color: Styles.Theme.textPrimary
                    font.pixelSize: Styles.Theme.fontSizeNormal
                    font.weight: Styles.Theme.fontWeightMedium
                }

                // 参数列表
                Repeater {
                    model: task ? Object.keys(task.parameters || {}) : []

                    RowLayout {
                        Layout.fillWidth: true

                        Text {
                            text: modelData + ":"
                            color: Styles.Theme.textSecondary
                            font.pixelSize: Styles.Theme.fontSizeSmall
                            Layout.preferredWidth: 100
                        }

                        Text {
                            text: task ? (task.parameters[modelData] || "") : ""
                            color: Styles.Theme.textPrimary
                            font.pixelSize: Styles.Theme.fontSizeSmall
                            Layout.fillWidth: true
                            wrapMode: Text.WordWrap
                        }
                    }
                }
            }
        }
    }

    // 辅助函数
    function getStageColor(stage) {
        switch(stage) {
        case 0: return Styles.Theme.warning   // Init
        case 1: return Styles.Theme.primary   // Running
        case 2: return Styles.Theme.info      // Cleanup
        case 3: return Styles.Theme.success   // Finished
        default: return Styles.Theme.textSecondary
        }
    }

    function formatStageText(stage) {
        switch(stage) {
        case 0: return qsTr("初始化")
        case 1: return qsTr("运行")
        case 2: return qsTr("清理")
        case 3: return qsTr("结束")
        default: return qsTr("未知")
        }
    }

    function formatSubTaskStatus(task) {
        if (!task) return qsTr("未知")
        var subTask = task.currentSubTask || qsTr("子任务%1").arg((task.currentTaskIndex || 0) + 1)
        var stageValue = (task.currentSubTaskStage !== undefined && task.currentSubTaskStage !== null) ? task.currentSubTaskStage : -1
        return qsTr("%1 · %2").arg(subTask).arg(formatStageText(stageValue))
    }

    function formatSubTaskProgress(task) {
        if (!task) return qsTr("0 / 0")
        var total = task.totalTasks || 0
        var current = (task.currentTaskIndex || 0) + 1
        if (total <= 0) {
            total = 1
            current = 0
        } else if (current > total) {
            current = total
        }
        return qsTr("%1 / %2").arg(current).arg(total)
    }

    function formatTaskName(task) {
        if (!task) return qsTr("未知任务")
        return task.taskName || task.chainId || qsTr("未知任务")
    }

    function getProgressColor(progress) {
        if (progress >= 80) return Styles.Theme.success
        if (progress >= 40) return Styles.Theme.info
        return Styles.Theme.warning
    }

    function formatTime(timestamp) {
        if (!timestamp) return qsTr("未设置")
        return new Date(timestamp).toLocaleString()
    }

    function formatDuration(seconds) {
        if (!seconds) return qsTr("不足1秒")
        var total = Math.max(0, seconds)
        var minutes = Math.floor(total / 60)
        var secs = total % 60
        if (minutes <= 0) {
            return qsTr("%1秒").arg(secs)
        }
        return qsTr("%1分%2秒").arg(minutes).arg(secs)
    }
}
